use rustcloud_core::{RustCloudApplicationBuilder, RegistryConfig, RegistryType, ApplicationConfig};
use rustcloud_registry::NacosRegistry;
use rustcloud_macros::remote_service;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use axum::{extract::State, routing::post, Router, Json};
use tracing::{info, Level};
use tracing_subscriber::FmtSubscriber;

// 用户数据结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
    pub age: u32,
}

#[derive(Debug, Deserialize)]
pub struct CreateUserRequest {
    pub name: String,
    pub email: String,
    pub age: u32,
}

// 定义用户服务接口
#[remote_service(\"user-service\")]
pub trait UserService {
    async fn get_user(&self, user_id: u64) -> Result<Option<User>, String>;
    async fn create_user(&self, request: CreateUserRequest) -> Result<User, String>;
    async fn list_users(&self) -> Result<Vec<User>, String>;
}

// 实现用户服务
#[derive(Clone)]
pub struct UserServiceImpl {
    // 简化实现，使用内存存储
    users: Arc<std::sync::RwLock<std::collections::HashMap<u64, User>>>,
    next_id: Arc<std::sync::atomic::AtomicU64>,
}

impl UserServiceImpl {
    pub fn new() -> Self {
        let users = Arc::new(std::sync::RwLock::new(std::collections::HashMap::new()));
        let next_id = Arc::new(std::sync::atomic::AtomicU64::new(1));
        
        // 添加一些示例数据
        {
            let mut users_lock = users.write().unwrap();
            users_lock.insert(1, User {
                id: 1,
                name: \"Alice\".to_string(),
                email: \"alice@example.com\".to_string(),
                age: 30,
            });
            users_lock.insert(2, User {
                id: 2,
                name: \"Bob\".to_string(),
                email: \"bob@example.com\".to_string(),
                age: 25,
            });
        }
        
        Self { users, next_id }
    }
}

#[async_trait::async_trait]
impl UserService for UserServiceImpl {
    async fn get_user(&self, user_id: u64) -> Result<Option<User>, String> {
        let users = self.users.read().map_err(|e| e.to_string())?;
        Ok(users.get(&user_id).cloned())
    }

    async fn create_user(&self, request: CreateUserRequest) -> Result<User, String> {
        let mut users = self.users.write().map_err(|e| e.to_string())?;
        let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        
        let user = User {
            id,
            name: request.name,
            email: request.email,
            age: request.age,
        };
        
        users.insert(id, user.clone());
        info!(\"Created user: {:?}\", user);
        Ok(user)
    }

    async fn list_users(&self) -> Result<Vec<User>, String> {
        let users = self.users.read().map_err(|e| e.to_string())?;
        Ok(users.values().cloned().collect())
    }
}

// HTTP路由处理器
async fn health_check() -> &'static str {
    \"OK\"
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    let subscriber = FmtSubscriber::builder()
        .with_max_level(Level::INFO)
        .finish();
    tracing::subscriber::set_global_default(subscriber)
        .expect(\"设置默认订阅者失败\");

    info!(\"启动用户服务...\");

    // 读取配置
    let app_config = ApplicationConfig {
        name: \"user-service\".to_string(),
        version: \"1.0.0\".to_string(),
        port: 8081,
        host: Some(\"127.0.0.1\".to_string()),
        group: Some(\"DEFAULT_GROUP\".to_string()),
        namespace: Some(\"public\".to_string()),
        metadata: std::collections::HashMap::new(),
    };

    // 创建注册中心
    let registry_config = RegistryConfig {
        registry_type: RegistryType::Nacos,
        server_addr: \"127.0.0.1:8848\".to_string(),
        namespace: Some(\"public\".to_string()),
        group: Some(\"DEFAULT_GROUP\".to_string()),
        username: None,
        password: None,
    };
    
    let registry = Arc::new(NacosRegistry::new(registry_config)?);

    // 创建服务实现
    let user_service = Arc::new(UserServiceImpl::new());

    // 创建HTTP路由
    let app = Router::new()
        .route(\"/health\", axum::routing::get(health_check))
        .route(\"/api/user-service/get_user\", post({
            let service = user_service.clone();
            move |Json(params): Json<serde_json::Value>| async move {
                let user_id: u64 = params.get(\"user_id\")
                    .and_then(|v| v.as_u64())
                    .ok_or_else(|| \"Missing user_id parameter\")?;
                
                match service.get_user(user_id).await {
                    Ok(user) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": user }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }))
        .route(\"/api/user-service/create_user\", post({
            let service = user_service.clone();
            move |Json(request): Json<CreateUserRequest>| async move {
                match service.create_user(request).await {
                    Ok(user) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": user }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }))
        .route(\"/api/user-service/list_users\", post({
            let service = user_service.clone();
            move |Json(_): Json<serde_json::Value>| async move {
                match service.list_users().await {
                    Ok(users) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": users }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }));

    // 创建并启动RustCloud应用
    let app_handle = {
        let registry_clone = registry.clone();
        tokio::spawn(async move {
            let rustcloud_app = RustCloudApplicationBuilder::from_config(app_config)
                .registry(registry_clone)
                .build();
            
            if let Err(e) = rustcloud_app.run().await {
                eprintln!(\"RustCloud应用启动失败: {}\", e);
            }
        })
    };

    // 启动HTTP服务器
    let listener = tokio::net::TcpListener::bind(\"127.0.0.1:8081\").await?;
    info!(\"用户服务在 http://127.0.0.1:8081 启动\");
    
    axum::serve(listener, app).await?;
    
    // 等待应用句柄完成
    let _ = app_handle.await;
    
    Ok(())
}
